﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GoodStuff.Heartbeat.Core.Data
{
    public class Aggregator
    {
        public void Aggregate(int sensorId, int channelId, DateTime until, int minutes)
        {
            using (var db = new GoodStuff.Data.DataContextBuilder().EnableObjectTracking().Build())
            {
                var sensorvalues = db.Where<Core.Data.SensorReading>(p => p.SensorID == sensorId && p.Channel == channelId && p.Timestamp <= until && p.Aggregated == false);

                var groups = sensorvalues.ToList().GroupBy(p => p.Timestamp.RoundTo(DateTimeRoundOption.Minute, minutes));

                var newInserts = groups.Select(p => new Data.SensorReading() { SensorID = sensorId, Channel = channelId, Timestamp = p.Key, Value = p.Average(g => g.Value), Aggregated = true });

                db.Select<Core.Data.SensorReading>().InsertAllOnSubmit(newInserts);
                db.Select<Core.Data.SensorReading>().DeleteAllOnSubmit(sensorvalues);
                db.SubmitChanges();
            }
        }
    }
}
